﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SMS_Agent.Model;
using SMS_Agent.Util;

namespace SMS_Agent.BLL
{
    public class User_BLL : BaseBLL_Provider
    {
        public static string Prefix_MaNV { get { return "NH"; } }

        public User_BLL() : base() { }

        public User_BLL(Entities entities) : base(entities) { }

        public user Create()
        {
            user obj = new user();

            //obj.MaKhachHang = GenerateNewMa(GetMaxMaKhachHang());

            return obj;
        }

        private string GenerateNewMa()
        {
            return GenerateNewMa(GetMaxMaNhanVien());
        }

        private string GenerateNewMa(string strMaxMa)
        {
            int intNewMa = int.Parse(strMaxMa.Replace(Prefix_MaNV, "")) + 1;

            string NewMa = Prefix_MaNV + intNewMa.ToString("D3");
            return NewMa;
        }

        private string GetMaxMaNhanVien()
        {
            string s = dbEntities.user.Max(p => p.user_name);
            return (s != null ? s : (Prefix_MaNV + "000"));
        }

        public user GetLogin(string UserName, string Password)
        {
            user obj = null;
            try
            {
                Password = RootStaticVar.Encrypt(Password);

                obj = dbEntities.user
                       .Where(p => (p.user_name == UserName)
                       && (p.password == Password)
                       ).SingleOrDefault();
            }
            catch (Exception ex)
            {
                ErrMsg = ex.Message;
            }
            return obj;
        }

        public user FilterById(string user_name)
        {
            user obj = null;
            try
            {
                obj = dbEntities.user
                       .Where(p => (p.user_name == user_name)
                       ).SingleOrDefault();
            }
            catch (Exception ex)
            {
                ErrMsg = ex.Message;
            }
            return obj;
        }

        public List<user> GetAll()
        {
            return dbEntities.user.ToList();
        }

        public List<user> Filter(bool isRefreshAll, string criteria)
        {
            List<user> list = null;

            if (criteria == null || criteria == "") { return GetAll(); }

            list = dbEntities.user
                //    .AsNoTracking()
                //list = query
                .Where(p =>
                    p.user_name.Contains(criteria)
                    )
                .ToList();

            return list;
        }

        public List<user> Filter(string criteria)
        {
            return Filter(true, criteria);
        }

        private bool CheckIfExist(string MaKhachHang)
        {
            return (FilterById(MaKhachHang) != null);
        }
    }
}